package com.lkm.app_ui.ui.fj;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.HandleDialog;
import com.lkm.app_ui.m.fun.FunItem;
import com.lkm.app_ui.netapi.AppApi;
import com.lkm.app_ui.ui.sale.p.PrintTask;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.comlib.ui.BaseHoldAdapter;
import com.lkm.comlib.ui.IHoldView;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.DateHelp;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.ServerTimeSync;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;



public class PayFjFragment extends MBaseFragment {
    
    FjInfo fjInfo = FjApp.install.getFjInfo();
    FjOrder fjOrder = null;


    private ItemsView itemsView;
    private FunView funView;

    @Override
    protected int configLayoutResID() {
        return R.layout.fj_fragment_pay;
    }

    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        itemsView = new ItemsView();
        funView = new FunView();
        binfjInfo();
    }

    

    private void reShow() {

        if (fjOrder != null) {
            List<FjOrder.FjItem> souceList = fjOrder.fjItems;

            itemsView.setSouceList(souceList);
            ((TextView) findViewById(R.id.tv_order_info)).setText(fjOrder.fjInfoNo);
        }
        FjWaitOrder fjWaitOrder = FjApp.install.getFjWaitOrder();

//        ((TextView) findViewById(R.id.tv_waitnum)).setText("" + fjWaitOrder.getSize());


    }


    

    private void binfjInfo() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnFjInfoEvent>() {

            @Override
            public void onReceiver(OnFjInfoEvent data) {

                
                if (fjOrder != null) {
                    holdTaskCollection().cancelAllTask();
                    RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                    return;
                }
                fjInfo = FjApp.install.getFjInfo();
                fjOrder = fjInfo == null ? null : fjInfo.getCurFjOrder();
                if (fjOrder == null) {
                    holdTaskCollection().cancelAllTask();
                    RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                } else {
                    reShow();
                }
            }

            @Override
            public Class<OnFjInfoEvent> getBusEventClass() {
                return OnFjInfoEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private class ItemsView {
        private ListView listView;
        private MAdapter adapter;
        private List<FjOrder.FjItem> souceList = new ArrayList<>();

        public void setSouceList(List<FjOrder.FjItem> souceList) {
            this.souceList = souceList;
            adapter.notifyDataSetChanged();
        }

        public ItemsView() {
            ((TextView) findViewById(R.id.tv_weight_unit_title)).setText("重量(" + RunTimeData.getAppWeightUnit() + ")");
            listView = findViewById(R.id.vg_list).findViewById(android.R.id.list);
            listView.setAdapter(adapter = new MAdapter());

        }


        private class MAdapter extends BaseHoldAdapter {
            public MAdapter() {
                super(holdCycleHelp());
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();

            }

            @Override
            public IHoldView createHoldView(int position, View convertView, ViewGroup parent) {
                return new MHoldView();
            }

            @Override
            public int getCount() {
                return CollectionHelp.getSize(souceList);
            }

            @Override
            public Object getItem(int position) {
                return souceList.get(position);
            }
        }

        private class MHoldView extends LinearLayout implements IHoldView<FjOrder.FjItem> {

            private TextView tv_name, tv_price_unit, tv_weight, tv_totalPrice, tv_no;

            public MHoldView() {
                super(getActivity());
                ViewHelp.inflate(getActivity(), R.layout.item_sales, this);
                tv_no = (TextView) this.findViewById(R.id.tv_no);
                tv_name = (TextView) this.findViewById(R.id.tv_name);
                tv_price_unit = (TextView) this.findViewById(R.id.tv_price_unit);
                tv_weight = (TextView) this.findViewById(R.id.tv_weight);
                tv_totalPrice = (TextView) this.findViewById(R.id.tv_totalPrice);

            }

            private int position;

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public Object binData(FjOrder.FjItem obj, int position, boolean isonPause) {
                this.position = position;


                setBackgroundColor(position % 2 == 1 ? Color.YELLOW : Color.TRANSPARENT);
                tv_no.setText("" + (position ));
                tv_name.setText(obj.goodsName);
                tv_price_unit.setText(SteelardHelp.formatMoney(obj.price));
//                tv_weight.setText(NumberHelp.formatMoney(obj.weight, 3, "--"));
                tv_weight.setText(obj.weight);

                tv_totalPrice.setText(obj.realWeight);

                setTag(obj);
                return null;
            }

        }   

    }

    private class FunView implements ChoiceCard.ChoiceCardBC {

        private ChoiceCard mChoiceCard;

        public FunView() {

            mChoiceCard = findViewById(R.id.ChoiceCard);
            mChoiceCard.setItemViewHeigth(ViewHelp.getPX(getActivity(), R.dimen.dp100px));
            mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item, R.layout.item, 1);

            mChoiceCard.setChoiceCardBC(this);
            initDatax();
            reOnKeyEvent();
        }

        private void initDatax() {
            List<FunItem> funItems = new ArrayList<>();
            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_PAY, "支付：确认提交", false));
            funItems.add(new FunItem("" + OnSteelyardKeyEvent.KEYCODE_9, OnSteelyardKeyEvent.KEYCODE_9 + "：退出"));

            ChoiceItem[] cis = new ChoiceItem[funItems.size()];
            int i = 0;
            for (FunItem funItem : funItems) {
                cis[i] = new ChoiceItem(funItem.id, funItem.name);
                cis[i].setTag(funItem);
                cis[i].setIsChoice(funItem.isChoice);
                i++;
            }

            mChoiceCard.binData(cis);
        }

        private void clickItem(int keyCode) {
            boolean hasItemFun = false;
            IChoiceItem[] items = mChoiceCard.getData();
            for (IChoiceItem item : items) {
                FunItem funItem = (FunItem) item.getTag();
                if (NumberHelp.toInt(funItem.id, -1) == keyCode) {
                    hasItemFun = true;
                    break;
                }
            }
            if (!hasItemFun) return;

            switch (keyCode) {
                case OnSteelyardKeyEvent.KEYCODE_PAY: {
                    holdTaskCollection().cancelAllTask();
                    // 当前没有在分拣的.那就要请求加载.
                    PayFjOrderTask task = new PayFjOrderTask();
                    task.action();
                    holdTaskCollection().add(task.execTask());
                }
                break;

                case OnSteelyardKeyEvent.KEYCODE_9: {
                    RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                }
                break;
            }

        }

        @Override
        public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
            if (c.getIsChoice()) {
                FunItem funItem = (FunItem) c.getTag();
                clickItem(NumberHelp.toInt(funItem.id, -1));
            }

        }

        
        private void reOnKeyEvent() {
            LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
                @Override
                public Class<OnSteelyardKeyEvent> getBusEventClass() {
                    return OnSteelyardKeyEvent.class;
                }

                @Override
                public void onReceiver(OnSteelyardKeyEvent data) {
                    if (!data.isIntercepted()) {
                        data.setIntercepted(true);

                        if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                            
                            RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                        } else {
                            clickItem(data.getKeyCode());
                        }

                    }
                }
            }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
        }


    }


    

    private class PayFjOrderTask extends TaskAdapter<Void, Void, ResponEntity<FjOrder>> {

        public PayFjOrderTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), PayFjOrderTask.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(getActivity(), "", getId());
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);


            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    String json = AppApi.fjUp(fjOrder, PayFjOrderTask.this);
                    ResponEntity<Void> re = ResponEntity.fromJson(json, null, "");

                    boolean isPaySuccess = re.isSuccess();

                    if (!isPaySuccess) {
                        ResponEntity<FjOrder> ree = new ResponEntity<>(re);
                        complete(ree);
                        return;
                    }
                    
                    FjOrder fjOrder = FjApp.install.getFjWaitOrder().popWaitOrder(null, null);
                    ResponEntity<FjOrder> ree = ResponEntity.success(fjOrder);
                    complete(ree);
                }
            });
        }

        @Override
        public void onEnd(boolean isCancel, ResponEntity<FjOrder> result) {
            super.onEnd(isCancel, result);
            ViewUIHelp.disProgressBar(getId());

            if (isCancel) {
                RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                return;
            }
            if (result.isSuccess()) {
                if (result.getData() == null) {
                    fjInfo.setCurFj(null, null);
                } else {
                    fjInfo.setCurFj(result.getData(), result.getData().findNext(null));
                }

                try {
                    
                    String print = new FjSalePrint().cretePrintContent(fjOrder, DateHelp.toString(DateHelp.DateFormatyyyy_MM_dd_HHmmss(Locale.getDefault()), ServerTimeSync.getInstance().getServerCurTime()), RunTimeData.steelyardInfo);
                    PrintTask.print(print, "");
                }catch (Exception e){}


                AppUIHelp.tryShowTipsSHORT("分拣订单-提交成功");

                AppUIHelp.tryShowTipsSHORT("请继续分拣订单");
                RouterUINavigation.getInstance().showFjOrder((BaseFragmentActivity) getActivity(), false);

            } else {
                new HandleDialog().show(getActivity(), result.getMsg(), OnSteelyardKeyEvent.KEYCODE_9, "重试（按9）", new Runnable() {
                    @Override
                    public void run() {
                        PayFjFragment.PayFjOrderTask.this.action();
                        PayFjFragment.PayFjOrderTask.this.execTask();
                    }
                }, new Runnable() {
                    @Override
                    public void run() {
                        RouterUINavigation.getInstance().dismiss(PayFjFragment.this);
                    }
                });
            }
        }
    }

}
